Sets
In Python, a set is very similar to a list, but with a few key differences.
- A set is unordered, meaning the elements are not stored in a specific order. If order is important, you should use a list.
- When printing a set, the elements sometimes appear in sorted order, but this is not guaranteed.
- A set can only contain unique elements. If you try to add a duplicate element to a set, it will be ignored.
my_set = {1, 2, 3}
print(my_set) # Output: {1, 2, 3}
my_set = {3, 2, 1}
print(my_set) # Output: {1, 2, 3}
1. Creating Sets
A set can be created using curly braces {}
with elements separated by commas. We can declare an empty set with set()
.
my_set = set()
my_set.add(1)
my_set.add(2)
my_set.add(3)
# equivalent to
my_set = {1, 2, 3}
Note:
my_set = {}
creates an empty dictionary in Python, not a set.
2. Set Operations
1. add()
We can add elements to a set using the add()
method.
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}
2. remove()
We can remove elements from a set using the remove()
method. If the element is not present in the set, a KeyError
will be raised.
my_set = {1, 2, 3}
my_set.remove(2)
print(my_set) # Output: {1, 3}
my_set.remove(4) # Raises KeyError
3. len()
You can call the len()
function on a set to get the number of elements in the set.
my_set = {1, 2, 3}
print(len(my_set)) # Output: 3
4. Loop over Sets
Just like with lists, we can loop over elements within a set using for
loops. The difference is that we can't access elements by index because sets are unordered. The order that we loop over a set is not guaranteed.
my_set = {1, 2, 3}
for element in my_set:
print(element)
5. Convert List into Set
We can also convert a list into a set by passing the list into the set()
function. We can then convert the set back into a list by passing it into the list()
function.
This is an easy way to remove duplicates from a list.
my_list = [1, 2, 3, 4, 5, 1, 2, 5]
my_set = set(my_list)
print(my_set) # Output: {1, 2, 3, 4, 5}
my_list_no_duplicates = list(my_set)
6. in
keyword
Just like with lists, we can also use the in
keyword to check if an element is present in a set.
my_set = {"Cat", "Dog", "Mouse"}
contains_cat = "Cat" in my_set # True
contains_lion = "Lion" in my_set # False